package com.sirdc.modules.sys.web;

import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.JqGrid;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.databean.SysDeptRoomDataBean;
import com.sirdc.modules.sys.databean.SysUserDataBean;
import com.sirdc.modules.sys.entity.SysDept;
import com.sirdc.modules.sys.entity.SysDeptRoom;
import com.sirdc.modules.sys.entity.SysLogin;
import com.sirdc.modules.sys.filter.RoomUserFilter;
import com.sirdc.modules.sys.filter.SysDeptRoomFilter;
import com.sirdc.modules.sys.service.SysDeptRoomService;
import com.sirdc.modules.sys.service.SysDeptService;
import com.sirdc.modules.sys.service.SysLoginService;
import com.sirdc.modules.sys.util.SysUserUtils;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.supervision.task.entity.RoomUserEntity;
import net.huashitong.supervision.task.service.RoomUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.CollationKey;
import java.text.Collator;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 科室信息维护
 */
@Controller
@RequestMapping("/sys/deptRoom")
public class SysDeptRoomController extends JsonBaseController {

    @Autowired
    private SysDeptRoomService service;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private RoomUserService roomUserService;


    //获取当前登录用户锁在科室；
    @ResponseBody
    @RequestMapping(value = "/getrooms", method = RequestMethod.GET)
    public Message getListRooms(SysDeptRoomFilter filter) {
        if ("".equals(filter.getDeptId()) || null == filter.getDeptId()) {
            return coverMessage("500", "单位编码不能为空");
        }
        String userId = SysUserUtils.getUserId();

        SysLogin user = loginService.getById(userId);
        String roomId = user.getRoomId();
        List<SysDeptRoom> listRoomById = new ArrayList<>();
        if (null != roomId) {

            SysDeptRoom byId = service.getById(roomId);
            listRoomById.add(byId);
        }
        return coverMessage("200", "科室返回成功", listRoomById);
    }


    @Override
    protected String getView(String view) {
        return "/modules/room/" + view;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String initPage(HttpServletRequest request, Model model) {
        String deptId = request.getParameter("deptId");
        String deptName = request.getParameter("deptName");
        model.addAttribute("deptId", deptId);
        model.addAttribute("deptName", deptName);
        return getView("query");
    }

    /**
     * 初始化数据
     *
     * @param filter
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public JqGrid query(@ModelAttribute SysDeptRoomFilter filter, HttpServletRequest request) {
        String userId = SysUserUtils.getUserId();
        if ("".equals(userId)) {
            return coverJqGrid(filter, null);
        }
        if (!"admin".equals(userId)) {
            filter.setDeptId(SysUserUtils.getDeptId());
        }

        List<SysDeptRoomDataBean> list = service.queryDeptListToModel(filter);
        return coverJqGrid(filter, list);
    }


    /**
     * 新增科室-对话框
     *
     * @param filter
     * @param model
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(@ModelAttribute SysDeptRoomFilter filter, Model model) {
        //根据自己的过滤规则过滤部门，将来可以考虑是否要修改成下拉树
        String userId = SysUserUtils.getUserId();
        List<SysDept> depts = new ArrayList<>();
        if (!"admin".equals(userId)) {//非管理员
            SysDept dept = sysDeptService.getById(SysUserUtils.getDeptId());
            depts.add(dept);
        } else {
            depts = sysDeptService.query();
        }
        model.addAttribute("SysDeptRoomFilter", filter);
        model.addAttribute("depts", depts);
        //查询所有分管领导
        List<SysUserDataBean> byDeptId = loginService.getFgLeader();
        List<SysUserDataBean> fgleaders = byDeptId.stream().filter(obj -> ("03").equals(obj.getRoleId())).collect(Collectors.toList());
        //名字首字母排序
        Collections.sort(fgleaders, new Comparator<SysUserDataBean>() {
            Collator collator = Collator.getInstance(Locale.CHINA);
            @Override
            public int compare(SysUserDataBean o1, SysUserDataBean o2) {
                CollationKey key1 = collator.getCollationKey(o1.getName());
                CollationKey key2 = collator.getCollationKey(o2.getName());
                return key1.compareTo(key2);
            }
        });
        model.addAttribute("fgLeaders", fgleaders);
        return getView("create");
    }

    /**
     * 新增-功能
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public Message create(@ModelAttribute SysDeptRoomFilter filter) {
        service.createDeptRoom(filter);
        return coverMessage("200");
    }

    @RequestMapping(value = "/filter")
    public String showUserList(Model model) {
        List<SysDept> depts = sysDeptService.query();
        model.addAttribute("depts", depts);
        SysDeptRoomFilter filter = new SysDeptRoomFilter();
        model.addAttribute("SysDeptRoomFilter", filter);
        return getView("filter");
    }

    /**
     * 删除操作
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete/{id}")
    public Message delete(@PathVariable List<String> id) {
        List<SysDeptRoom> needUpdate = new ArrayList<>();
        for (String s : id) {
            SysDeptRoom object = service.getById(s);
            object.setState("03");  //停用
            needUpdate.add(object);
        }
        service.batchUpdate(needUpdate);
        return coverMessage("200", "删除成功");
    }

    /**
     * 修改科室信息-页面
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String showEditView(Model model, @PathVariable String id) {
        //根据自己的过滤规则过滤部门，将来可以考虑是否要修改成下拉树
        List<SysDept> depts = sysDeptService.query();
        SysDeptRoom deptRoom = service.getById(id);
        model.addAttribute("SysDeptRoomFilter", deptRoom);
        model.addAttribute("depts", depts);
        List<SysUserDataBean> byDeptId = loginService.getByDeptId(SysUserUtils.getDeptId());
        List<SysUserDataBean> fgleaders = byDeptId.stream().filter(obj -> ("03").equals(obj.getRoleId())).collect(Collectors.toList());
        model.addAttribute("fgLeaders", fgleaders);
        return getView("edit");
    }

    /**
     * 修改科室信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Message update(@ModelAttribute SysDeptRoomFilter filter) {
        if (StringUtils.isNotBlank(filter.getSysId())) {
            try {
                SysDeptRoom deptRoom = service.getById(filter.getSysId());
                deptRoom.setState(filter.getState());
                deptRoom.setDeptId(filter.getDeptId());
                deptRoom.setOrderBy(filter.getOrderBy());
                deptRoom.setRoomName(filter.getRoomName());
                if (ObjectUtils.isNotBlank(filter.getFgLeader())) {
                    deptRoom.setFgLeader(filter.getFgLeader());
                }
                service.update(deptRoom);
            } catch (Exception e) {
                return coverMessage("500", e.getMessage());
            }
            return coverMessage("200");
        } else {
            return coverMessage("500");
        }
    }


    //科室-人员 信息维护
    //打开添加科室人员的页面
    @RequestMapping(value = "/roomUser/{id}", method = RequestMethod.GET)
    public String showRoomUserView(Model model, @PathVariable String id) {
        //根据自己的过滤规则过滤部门，将来可以考虑是否要修改成下拉树
        List<SysDept> depts = sysDeptService.query();
        SysDeptRoom deptRoom = service.getById(id);
        model.addAttribute("SysDeptRoomFilter", deptRoom);

        model.addAttribute("roomId", id);
        return getView("roomUser");
    }

    /**
     * 修改科室人员信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/editroomuser", method = RequestMethod.POST)
    public Message editRoomUser(@ModelAttribute SysDeptRoomFilter filter) {
        String checkIds = filter.getCheckIds();
        if(ObjectUtils.isBlank(checkIds))
        {
            coverMessage("500","请先选择人员");
        }
        String[] userIds = checkIds.split(",");//分割人员；
      /*  for (String userId : userIds) {
            SysLogin byId = loginService.getById(userId);
            byId.setRoomId(filter.getRoomId());
            loginService.update(byId);
        }*/

        List<RoomUserEntity> listEntitys = new ArrayList<>();
        for (String userId : userIds) {

            RoomUserEntity entity = new RoomUserEntity();
            entity.setRoomId(filter.getRoomId());
            entity.setUserId(userId);
            entity.setValid(1);
            //roomUserService.save(entity);
            RoomUserEntity isExit = roomUserService.getUserByRoomIdAndUserId(filter.getRoomId(), userId);
            if(null==isExit){

                listEntitys.add(entity);
            }
        }
        roomUserService.batchSave(listEntitys);

        return coverMessage("200");

    }

    @ResponseBody
    @RequestMapping(value = "/romuser", method = RequestMethod.GET)
    public Message getRoomUser(HttpServletRequest request) {

        String roomId = request.getParameter("roomId");
        String deptId = SysUserUtils.getDeptId();
        /*if("".equals(deptId))
        {
            deptId="20190718100000000047";
        }*/

//        List<SysUserDataBean> byDeptId = loginService.getByRoomId(roomId);
        List<SysUserDataBean> byDeptId = loginService.getByDeptId(deptId);
        List<RoomUserFilter> roomUserList = new ArrayList<>();
        for (SysUserDataBean userBean : byDeptId) {
            RoomUserFilter dto = new RoomUserFilter();
            String userId = userBean.getUserId();
            RoomUserEntity entity = roomUserService.getUserByRoomIdAndUserId(roomId, userId);
            SysLogin loginUser = loginService.getById(userId);
            dto.setUserName(loginUser.getUsername());
            dto.setUserId(loginUser.getSysId());
            dto.setRoomId("");
            if(entity==null){
                dto.setChecked(0);
            }else {
                dto.setChecked(1);
                dto.setRoomId(entity.getRoomId());
            }
            roomUserList.add(dto);
        }
       /* for (SysUserDataBean item : byDeptId) {
            RoomUserFilter dto = new RoomUserFilter();
            dto.setUserName(item.getName());
            dto.setUserId(item.getUserId());
            dto.setRoomId("");
            if (!"".equals(item.getRoomId()) && null != item.getRoomId()) {
                if (roomId.equals(item.getRoomId())) {
                    dto.setChecked(1);
                    dto.setOtherCheck(0);
                } else {
                    dto.setOtherCheck(1);
                    dto.setChecked(0);
                }
                dto.setRoomId(item.getRoomId());
            } else {
                dto.setChecked(0);
                dto.setOtherCheck(0);
            }
            roomUserList.add(dto);
        }*/


        return coverMessage("200", "返回单位科室人员", roomUserList);

    }


}
